package org.sidora.strata.explorer;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.swing.DefaultListModel;
import javax.swing.UIManager;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Feature;
import org.sidora.core.KeyObject;
import org.sidora.core.Sector;
import org.sidora.core.Zone;
import org.sidora.core.util.AbstractInventory;
import org.sidora.core.util.LoggerProvider;
import org.sidora.core.util.ParameterCollector;
import org.sidora.strata.SidoraTools;
import org.sidora.strata.Storage;



/**
 * Feature Explorer Form
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class FeatureExplorerTopComponent extends TopComponent {
    
    private static FeatureExplorerTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "FeatureExplorerTopComponent";
    
    private FeatureExplorerTopComponent() {
        System.setProperty(
            "Quaqua.tabLayoutPolicy","wrap"
         );
         // set the Quaqua Look and Feel in the UIManager
         try { 
              UIManager.setLookAndFeel(
                  "ch.randelshofer.quaqua.QuaquaLookAndFeel"
              );
         // set UI manager properties here that affect Quaqua
         
         } catch (Exception e) {
             // take an appropriate action here
             
         }
         // insert your application initialization code here
        initComponents();
        setName(NbBundle.getMessage(FeatureExplorerTopComponent.class, "CTL_FeatureExplorerTopComponent"));
        setToolTipText(NbBundle.getMessage(FeatureExplorerTopComponent.class, "HINT_FeatureExplorerTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jListFeature = new javax.swing.JList();
        jListFeature.putClientProperty(
            "Quaqua.List.style", "striped"
        );
        jButtonDelFeature = new javax.swing.JButton();
        jButtonDelFeature.putClientProperty(
            "Quaqua.Button.style","square"
        );
        jButtonAddFeature = new javax.swing.JButton();
        jButtonAddFeature.putClientProperty(
            "Quaqua.Button.style","square"
        );

        jListFeature.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListFeatureValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jListFeature);

        org.openide.awt.Mnemonics.setLocalizedText(jButtonDelFeature, "-");
        jButtonDelFeature.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelFeatureActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButtonAddFeature, "+");
        jButtonAddFeature.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddFeatureActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(44, Short.MAX_VALUE)
                .add(jButtonAddFeature)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButtonDelFeature))
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
        );

        layout.linkSize(new java.awt.Component[] {jButtonAddFeature, jButtonDelFeature}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonDelFeature)
                    .add(jButtonAddFeature)))
        );

        layout.linkSize(new java.awt.Component[] {jButtonAddFeature, jButtonDelFeature}, org.jdesktop.layout.GroupLayout.VERTICAL);

    }// </editor-fold>//GEN-END:initComponents
    
    private void jListFeatureValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListFeatureValueChanged
        SidoraTools.showElement();
            Storage.getFeatureAction().saveFields();
            Storage.setFeature((Feature) jListFeature.getSelectedValue());
            Storage.getFeatureAction().actionPerformed();            
            Storage.setContext(null);
            Storage.getContextExplorerAction().fillContextItems();
        /*if (jListFeature.getValueIsAdjusting()){
            SidoraTools.showElement();
            Storage.getFeatureAction().saveFields();
            Storage.setFeature((Feature) jListFeature.getSelectedValue());
            Storage.getFeatureAction().actionPerformed();            
            //Storage.getContextExplorerAction().fillContextItems();
            
            //Storage.getContextFormAction().saveFields();
            Storage.setContext(null);
            Storage.getContextExplorerAction().fillContextItems(); 
        }
         */
    }//GEN-LAST:event_jListFeatureValueChanged
    
    private void jButtonAddFeatureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddFeatureActionPerformed
        addFeature();
        fillFeatureItems();
    }//GEN-LAST:event_jButtonAddFeatureActionPerformed
    
    private void jButtonDelFeatureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelFeatureActionPerformed
        delFeature();
    }//GEN-LAST:event_jButtonDelFeatureActionPerformed
    
    private void delFeature() {
        Feature feature = (Feature) jListFeature.getSelectedValue();
        AbstractInventory.deleteObject(feature);
        fillFeatureItems();
        Storage.setFeature(null);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddFeature;
    private javax.swing.JButton jButtonDelFeature;
    private javax.swing.JList jListFeature;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized FeatureExplorerTopComponent getDefault() {
        if (instance == null) {
            instance = new FeatureExplorerTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the FeatureExplorerTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized FeatureExplorerTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find FeatureExplorer component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof FeatureExplorerTopComponent) {
            return (FeatureExplorerTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        this.setDisplayName("Feature");
    }
    
    public void componentClosed() {
        Storage.setFeature(null);
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return FeatureExplorerTopComponent.getDefault();
        }
    }
    
    private static void addFeature(){
        Zone zone = Storage.getZone();
        Sector sector = Storage.getSector();
        
        if (zone != null && sector != null){
            ParameterCollector param = new ParameterCollector();
            Feature.Inventory fi = new Feature.Inventory();
            TreeSet <Sector> sectors = new TreeSet<Sector>();
            sectors.add(sector);
            
            param.put("zone",zone);
            param.put("action",Storage.getSite().getDefaultAction());
            
            Feature feature = null;
            try {
                feature = fi.getNewObject(param);
                //feature.setName("New feature");
                feature.setSectors(sectors);
                
                fi.setObject(feature);
            }catch (Exception e1) {
                LoggerProvider.getInstance().log(Level.WARNING,"Exception",e1);
            }
        }else{
            LoggerProvider.getInstance().fine("No hay un Site seleccionado.");
        }
    }
    
    public void fillFeatureItems(){
        //long lng = System.nanoTime();
        //System.out.println("Inici: "+(lng - System.nanoTime()));
        Zone zone = Storage.getZone();
        //        System.out.println("Obtenir Zona: "+(lng - System.nanoTime()));
        Sector sector = Storage.getSector();
        //        System.out.println("Obtenir Sector: "+(lng - System.nanoTime()));
        if (sector != null){
            DefaultListModel featureModel = new DefaultListModel();
         //           System.out.println("Crea Model: "+(lng - System.nanoTime()));
            try {
                List<Feature> list = Feature.Inventory.getList(sector);//Site.Inventory.getList();
           //             System.out.println("Obtenir llista de fets: "+(lng - System.nanoTime()));
                //TreeSet <Feature> features = new TreeSet<Feature>();
                
                TreeSet <Feature> features = new TreeSet<Feature>(list);
             //           System.out.println("Ordenar llista: "+(lng - System.nanoTime()));
                //Iterator iter2 = list.iterator();
                //while(iter2.hasNext()){
                //    Feature feature = (Feature) iter2.next();
                //    features.add(feature);
                //}
                
                //Ho fiquem en un TreeSet per a tenir la col�lecci� ordenada
                Iterator iter = features.iterator();
                //Iterator iter = list.iterator();
             //           System.out.println("Obtenir iterador: "+(lng - System.nanoTime()));
                while (iter.hasNext()){
                    featureModel.addElement(iter.next());
                }
               //                 System.out.println("Copia llista a model: "+(lng - System.nanoTime()));
                
            } catch (Exception e1) {
                LoggerProvider.getInstance().log(Level.WARNING,"Exception",e1);
            }
            jListFeature.setModel(featureModel);
        } else {
            jListFeature.setModel(new DefaultListModel());
                 //   System.out.println("Assignar Model: "+(lng - System.nanoTime()));
        }
    }
    
}
